package com.lsj.core.extend.rest;

import com.lsj.core.constant.response.ResponseConstant;
import com.lsj.core.response.BasicResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.StringJoiner;

public class BasicRest<T> {

    public BasicResponse<T> setSuccess(String msg,T data){
        return setResult(ResponseConstant.SUCCESS,msg,data);
    }
    public BasicResponse<T> setSuccess(T data){
        return setResult(ResponseConstant.SUCCESS,null,data);
    }
    public BasicResponse<T> setSuccess(String msg){
        return setResult(ResponseConstant.SUCCESS,msg,null);
    }
    public BasicResponse<T> setSuccess(){
        return setResult(ResponseConstant.SUCCESS,null,null);
    }
    public BasicResponse<T> setFail(String msg){
        return setResult(ResponseConstant.FAIL,msg,null);
    }
    public BasicResponse<T> setValidFail(BindingResult result){
        StringJoiner joiner = new StringJoiner(",");
        for(ObjectError err : result.getAllErrors()){
            joiner.add(err.getDefaultMessage());
        }
        return setResult(ResponseConstant.FAIL,joiner.toString(),null);
    }


    private BasicResponse<T> setResult(int code,String msg,T data){
        return new BasicResponse(code,msg,data);
    }
}
